package com.freedom.supercoin.base_library.utils;

import android.app.Activity;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;

/**
 *     WebView 工具类
 */

public class WebViewUtils {

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void initWebView(final Activity activity, final WebView webView){

        webView.setDrawingCacheEnabled(true);
        webView.setHorizontalFadingEdgeEnabled(false);
        webView.setVerticalFadingEdgeEnabled(false);

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setAppCacheEnabled(false);//启用缓存
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);//设置缓存模式
        settings.setBlockNetworkImage(false);
        // 解决图片不显示
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ){
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
//        settings.setAllowFileAccess(true);
//        settings.setDatabaseEnabled(true);
        settings.setDefaultTextEncodingName("utf-8");

        settings.setDomStorageEnabled(true);
        settings.setAppCacheMaxSize(1024*1024*8);
        String appCachePath = activity.getCacheDir().getAbsolutePath();
        settings.setAppCachePath(appCachePath);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);


        //强制调节字体大小，单行显示，不会为系统字体大小设置改变页面布局
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
        }else {
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }

        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){
                    webView.goBack();
                    return true;
                }
                return false;
            }
        });


    }
}
